package com.dosh;

import java.util.Date;
import android.app.Activity;
import android.database.Cursor;


/**
 * The Job class describes an entry in the Job or Job_Done table.
 * A Job is generated when the user selects a recapitulation for a new Planning.
 * The fields job_ID, amount, expiring and planning are necessary for a table entry.
 */

public class Job extends Activity{
	/**
	 * The ID of the Job entry
	 */
	public long job_ID;
	/**
	 * The Jobs amount
	 */
	public long amount;
	/**
	 * The date when the job should be executed
	 */
	public Date expiring;
	/**
	 * A reference to the related Planning
	 */
	public Planning planning;
	/**
	 * Informs if the Job is done or not and about the table the job is
	 */
	public boolean done;
	
	/**
	 * This Constructor is used, if there is no entry in the database.
	 * @param dba A reference to the DBAdapter
	 */
	public Job(Date start, long amount, Planning planning, DBAdapter dba) {
		
		this.expiring = start;
		this.planning = planning;
		this.amount = amount;
		this.done=false;
		dba.open();
		this.job_ID = dba.insertJob(""+start.getDate()+"."+start.getMonth()+"."+start.getYear(), amount, planning.planning_ID);
		dba.close();
	}
	/**
	 * This Constructor is used, if there an entry already exists in the database.
	 * @param dba A reference to the DBAdapter
	 */
	public Job(long job_ID, DBAdapter dba){
		
		this.job_ID = job_ID;
		dba.open();
		Cursor pCursor = dba.SELECTbyId("Job", job_ID);
		dba.close();
		String[] helpdate = new String[3];
		helpdate = pCursor.getString(1).split("\\.");
		this.expiring = new Date(Integer.parseInt(helpdate[2]), Integer.parseInt(helpdate[1]), Integer.parseInt(helpdate[0]));
		this.amount = pCursor.getLong(2);
		this.planning = new Planning((int)pCursor.getLong(3), dba);
	}
	/**
	 * This function finishes a Job, delete its entry out in the Job table and creates it in the JOb_Done table
	 * The function also charges the Jobs amount against the related Budget.
	 * @param bud The related Budget
	 * @param dba A reference to the DBAdapter
	 */
	public void jobDone(DBAdapter dba, Budget bud){
		this.done=true;
		dba.open();
		dba.delete("Job",this.job_ID);
		this.job_ID=dba.insertJobDone(""+this.expiring.getDate()+"."+this.expiring.getMonth()+"."+this.expiring.getYear(), this.amount, this.planning.planning_ID);
		dba.close();
		bud.actual_amount=-this.amount;
	}
	
}
